<?php
// +----------------------------------------------------------------------
// | DTPHP 
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://dtphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yyj <qingchen.yyj@gmail.com>
// +----------------------------------------------------------------------


namespace app\common\utils;


class Tools
{
    /**
     * 将查询的二维对象转换成二维数组
     * @param array $res
     * @param string $key 允许指定索引值
     * @return array
     */
    public static function buildArrFromObj($res, $key = '')
    {
        $arr = [];
        foreach ($res as $value) {
            $value = $value->toArray();
            if ($key) {
                $arr[$value[$key]] = $value;
            } else {
                $arr[] = $value;
            }
        }

        return $arr;
    }

    /**
     * 将二维数组变成指定key
     * @param $array
     * @param $keyName
     * @return array
     */
    public static function buildArrByNewKey($array, $keyName = 'id')
    {
        $list = array();
        foreach ($array as $item) {
            $list[$item[$keyName]] = $item;
        }
        return $list;
    }

    /**
     * 将一维数组变成指定key二维数组
     * @param $array
     * @param $keyName
     * @return array
     */
    public static function buildOneArrByNewTwoKey($array, $keyName = 'id')
    {
        $list = array();
        foreach ($array as $item) {
            array_push($list, [$keyName => $item]);
        }
        return $list;
    }

}